<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggleDialog">
      <span v-if="!fullLocation" class="placeholder">{{placeholder}}</span>
      <span v-else class="value">{{ fullLocation }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="active">
      <div v-if="loading" class="loading"></div>
      <template v-else>
        <span @click="changeItem(item)" class="ellipsis" v-for="item in currList" :key="item.id">{{ item.name }}</span>
      </template>
    </div>
  </div>
</template>
<script>
import { ref, computed, reactive } from 'vue'
import { onClickOutside } from '@vueuse/core'
import axios from 'axios'
export default {
  name: 'XtxCity',
  props: {
    fullLocation: {
      type: String,
      default: ''
    },
    placeholder:{
      type:String,
      default:'请选择配送地址'
    }
  },
  setup(props,{emit}) {
    // 控制展开收起,默认收起
    const active = ref(false)
    // 定义一个城市数据供模版使用
    const cityData = ref([])
    // 定义一个是否加载数据的loading
    const loading = ref(false)
    //定义显示的方法
    const openDialog = () => {
      loading.value = true
      active.value = true
      //打开列表时获取城市数据
      getCityData().then(res => {
        cityData.value = res
        loading.value = false
      })
      //清空地址
      for (const key in changeResult) {
        changeResult[key] = ''
      }
    }
    //定义隐藏的方法
    const closeDialog = () => {
      active.value = false
    }
    // 切换显示与隐藏
    const toggleDialog = () => {
      active.value ? closeDialog() : openDialog()
    }
    //点击地址下拉元素外面关闭下拉元素
    let target = ref(null) //获取监听的元素
    onClickOutside(target, () => {
      closeDialog()
    })
    // 获取城市数据
    const getCityData = () => {
      // 这个位置可能有异常操作，封装成promise
      return new Promise((resolve, reject) => {
        if (window.cityData) {
          //有缓存时
          resolve(window.cityData)
        } else {
          //没有缓存时
          const url = 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
          axios.get(url).then(data => {
            //缓存地址数据
            window.cityDat = data.data
            //返回数据
            resolve(window.cityDat)
          })
        }
      })
    }
    // 通过计算属性分别计算出 省 市 县/区 的数据
    const currList = computed(() => {
      //默认数据为全部省份
      let List = cityData.value
      //当点击了某一个省份展示该省的所有市的信息
      if (changeResult.provinceCode && changeResult.provinceName) {
        List = List.find(p => p.code === changeResult.provinceCode).areaList
      }
      //当点击了某一个市份展示该市的所有县/区的信息
      if (changeResult.cityCode && changeResult.cityName) {
        List = List.find(c => {
          return c.code === changeResult.cityCode
        }).areaList
      }

      return List
    })

    //监听用户点击 省，市 展示 市列表和地区列表
    const changeResult = reactive({
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      countyCode: '',
      countyName: '',
      fullLocation: ''
    })

    const changeItem = (item) => {
      // 省份
      if (item.level == 0) {
        changeResult.provinceCode = item.code
        changeResult.provinceName = item.name
      }
      // 市
      if (item.level === 1) {
        changeResult.cityCode = item.code
        changeResult.cityName = item.name
      }
      // 县/地区
      if (item.level === 2) {
        changeResult.countyCode = item.code
        changeResult.countyName = item.name
        //拼接地址
        changeResult.fullLocation = `${changeResult.provinceName}-${changeResult.cityName}-${changeResult.countyName}`
        //关闭下拉地址
        active.value = false
        //提交数据给父组件
        emit('change',changeResult)
      }
    }

    return {
      active,
      toggleDialog,
      target,
      loading,
      currList,
      changeItem
    }
  }
}
</script>


<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;

  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;

    &.active {
      background: #fff;
    }

    .placeholder {
      color: #999;
    }

    .value {
      color: #666;
      font-size: 12px;
    }

    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }

  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;

    >span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;

      &:hover {
        background: #f5f5f5;
      }
    }

    .loading {
      height: 290px;
      width: 100%;
      background: url(../../assets/image/loading.gif) no-repeat center;
    }
  }
}
</style>